import {useSystemStore, useUserStore} from '@/store'
import {connectSocket as connect, closeSocket as close} from './socket'
import {IResponseData} from '@/service/api/type'

// 连接socket
export const connectSocket = async (): Promise<void | string> => {
  const systemStore = useSystemStore()
  const userStore = useUserStore()
  return new Promise<void | string>((resolve, reject) => {
    if (systemStore.socketStatus === 1) {
      // 已连接
      resolve()
      return
    }
    if (userStore.userInfo && userStore.userInfo.userId) {
      connect(userStore.userInfo?.userId).then(() => {
        console.log('[Socket]', '已连接')
        systemStore.socketStatus = 1
        onSocketMessage()
        uni.onSocketClose(() => {
          systemStore.socketStatus = -1
          console.log('[Socket]', '已关闭')
        })
        resolve()
      }).catch(err => {
        if (err !== '未登录' && err !== '正在连接') {
          console.error(err)
        }
      })
    } else {
      reject('未登录')
    }
  })
}

// 关闭socket
const closeSocket = async (): Promise<void> => {
  const systemStore = useSystemStore()
  uni.onSocketClose(res => {
    systemStore.socketStatus = -1
    console.log('[Socket]', '已关闭')
  })
  await close().then(res => {

  }).catch(err => {
    if (err.errMsg === 'closeSocket:fail WebSocket is not connected') return
    console.error(err)
  })
}

// Socket消息监听器
export const onSocketMessage = (): void => {
  uni.onSocketMessage(res => {
    const data: IResponseData<any> = JSON.parse(res.data as string)

  })
}
